/*
 * 微信公众平台(JAVA) SDK
 *
 * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
 *
 * http://www.weixin4j.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.czmh.etc.onlinepubsys.wx.loader;

import com.alibaba.fastjson.JSON;
import com.czmh.etc.onlinepubsys.constants.RedisKey;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.weixin4j.loader.ITokenLoader;
import org.weixin4j.model.base.Token;

/**
 * @author Eric
 * @since 0.1.0
 */
@Component
public class WxTokenLoader implements ITokenLoader {

    private Logger logger = LoggerFactory.getLogger(WxTokenLoader.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * AccessToken对象
     */
    private Token token = null;


    @Override
    public Token get() {
        Object o = redisUtil.get(RedisKey.WECHAT_ALL_ACCESS_TOKEN);
        logger.info("getToken:" + JSON.toJSONString(o));
        String v = o != null ? o.toString() : null;
        if (null == o) {
            token = null;
        } else {
            WxToken wxToken = JSON.parseObject(v, WxToken.class);
            token = JSON.parseObject(v, Token.class);
            //根据token创建时间和超时时间间隔计算新的详细超时时间
            token.setExpires_in(wxToken.getExpires_in(), wxToken.getCreate_time());
        }
        return (token == null
                || StringUtils.isEmpty(token.getAccess_token())
                || token.isExprexpired()) ? null : token;
    }

    @Override
    public void refresh(Token token) {
        logger.info("refreshToken:" + JSON.toJSONString(token));
        if (null == token || StringUtils.isEmpty(token.getAccess_token())) {
            throw new IllegalStateException("access_token is null or empty");
        }
        if (token.getCreate_time() <= 0) {
            throw new IllegalStateException("createtime can not be zero");
        }
        if (token.isExprexpired()) {
            throw new IllegalStateException("access_token is exprexpired");
        }
        this.token = token;
        redisUtil.set(RedisKey.WECHAT_ALL_ACCESS_TOKEN, JSON.toJSONString(token));
    }

}
